package com.common.function.file;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author ben.huang
 */
public class FileFunction {
    public void processFile (String fileName, Function<String,String> processingStrategy) throws IOException {
        //supplier 相当于生产者，调用该函数会获取到文件地读取流
        Supplier<BufferedReader> fileReadSupplier = () ->{
            try {
                return new BufferedReader(new FileReader(fileName));
            } catch (FileNotFoundException e) {
                throw new RuntimeException("error opening file"+e);
            }
        };

        //相当于一个消费者，根据传入的函数去消费每一行读取到地数据
        Consumer<String> fileProcessor = line ->{
            String apply = processingStrategy.apply(line);
            System.out.println(apply);
        };

        //获取输入流
        BufferedReader reader = fileReadSupplier.get();
        String line;
        //依次处理每行输入流
        while((line = reader.readLine()) != null){
            fileProcessor.accept(line);
        }
    }
}
